<style lang="scss">
.ivu-modal-wrap {
  display: flex;
  align-items: center;
  justify-content: center;
  .ivu-modal{
    top: 0;
  }
}
</style>
<template>
  <div class="content">
    <Breadcrumb>
      <BreadcrumbItem to="/index">首页</BreadcrumbItem>
      <BreadcrumbItem>教师管理</BreadcrumbItem>
    </Breadcrumb>
    <Form inline :label-width="70" label-position="left" :model="search">
      <Button type="success" style="margin-right: 30px" @click="addModal = true">添加</Button>
      <FormItem label="姓名">
        <Input type="text" v-model="search.name" placeholder="请输入姓名检索"/>
      </FormItem>
      <FormItem label="用户名">
        <Input type="text" v-model="search.username" placeholder="请输入用户名检索"/>
      </FormItem>
      <FormItem label="电话号码">
        <Input type="text" v-model="search.phone" placeholder="请输入电话号码检索"/>
      </FormItem>
      <Button type="primary" style="margin-left: 30px" @click="searchClick">搜索</Button>
    </Form>
    <Table stripe row-key="id" :columns="columns" :data="data"></Table>
    <Page :current="current" :total="total" :page-size="pageSize" show-total show-sizer show-elevator :styles="{marginTop: '20px'}" @on-change="pageChange" @on-page-size-change="pageSizeChange" />
    <Modal
        v-model="modalShow"
        :title="addModal ? '添加老师' : editModal ? '修改老师' : '' + '灵异老师'"
        cancel-text="取消"
        class-name="center-modal"
        @on-visible-change="modalChange">
      <Form :model="form" :label-width="80" ref="modalForm" :rules="rules">
        <FormItem label="姓名" prop="name">
          <Input v-model="form.name" placeholder="请输入姓名"/>
        </FormItem>
        <FormItem label="性别" prop="sex">
          <RadioGroup v-model="form.sex">
            <Radio :label="1">男</Radio>
            <Radio :label="2">女</Radio>
          </RadioGroup>
        </FormItem>
        <FormItem label="用户名" prop="username">
          <Input v-model="form.username" placeholder="请输入用户名"/>
        </FormItem>
        <FormItem label="密码" prop="password">
          <Input v-model="form.password" placeholder="请输入密码(不填默认为123456)"/>
        </FormItem>
        <FormItem label="电话" prop="phone">
          <Input v-model="form.phone" placeholder="请输入电话"/>
        </FormItem>
        <FormItem label="状态">
          <i-switch v-model="form.status" size="large">
            <span slot="open">启用</span>
            <span slot="close">禁用</span>
          </i-switch>
        </FormItem>
      </Form>
      <div slot="footer">
        <Button type="text" size="large" @click="modalShow = false">取消</Button>
        <Button type="primary" size="large" @click="submit">{{ addModal ? '添加' : editModal ? '修改' : '' + '灵异' }}</Button>
      </div>
    </Modal>
    <Modal
        v-model="menuTree"
        title="树形菜单"
        cancel-text="取消"
        class-name="center-modal"
        :z-index="99999"
        @on-cancel="menuTree = false">
      <Tree :data="menuTreeData" ref="tree" show-checkbox></Tree>
      <div slot="footer">
        <Button type="primary" size="large" @click="menuTreeOkClick">确定</Button>
      </div>
    </Modal>
  </div>
</template>

<script>
export default {
  name: 'Teacher',
  data: function () {
    return {
      columns: [
        {
          type: 'index'
        },
        {
          title: '姓名',
          key: 'name'
        },
        {
          title: '用户名',
          key: 'username'
        },
        {
          title: '联系电话',
          key: 'phone'
        },
        {
          title: '状态',
          render: (h, params) => {
            return h('i-switch', {
              props: {
                value: params.row.status,
                size: 'large'
              },
              scopedSlots: {
                open: () => h('span', '启用'),
                close: () => h('span', '停用')
              },
              on: {
                'on-change': status => {
                  this.form = { ...params.row }
                  this.form.status = status
                  this.status(params)
                }
              }
            })
          }
        },
        {
          title: '创建时间',
          key: 'createTime'
        },
        {
          title: '操作',
          key: 'action',
          align: 'center',
          width: '260px',
          render: (h, params) => {
            return h('div', [
              h('Button', {
                props: {
                  type: 'warning',
                  size: 'small'
                },
                style: {
                  marginRight: '5px'
                },
                on: {
                  click: () => {
                    this.form = { ...params.row }
                    this.editModal = true
                  }
                }
              }, '修改'),
              h('Button', {
                props: {
                  type: 'error',
                  size: 'small'
                },
                style: {
                  marginRight: '5px'
                },
                on: {
                  click: () => {
                    this.$Modal.confirm({
                      title: '删除提示',
                      content: '是否确认删除?',
                      okText: '确定',
                      cancelText: '取消',
                      onOk: () => {
                        this.$http.delete(`teachers?id=${params.row.id}`).then(res => {
                          if (res.code === 200) {
                            this.getData()
                            this.$Message.success(res.msg)
                          }
                        })
                      }
                    })
                  }
                }
              }, '删除'),
              h('Button', {
                props: {
                  type: 'success',
                  size: 'small'
                },
                on: {
                  click: () => {
                    this.menuUserId = params.row.id
                    this.$http.get(`getUserMenu?userId=${this.menuUserId}&type=2`).then(res => {
                      if (res.code === 200) {
                        this.menuTreeData = res.data.tree
                        this.menuTree = true
                      }
                    })
                  }
                }
              }, '权限分配')
            ])
          }
        }
      ],
      data: [],
      addModal: false,
      editModal: false,
      editRoleModal: false,
      form: {
        status: true
      },
      rules: {
        name: [
          {
            required: true,
            type: 'string',
            message: '姓名不能为空',
            trigger: 'blur'
          },
          {
            min: 2,
            max: 30,
            message: '姓名长度在2-30位之间',
            trigger: 'blur'
          }
        ],
        sex: [
          {
            required: true,
            type: 'number',
            message: '请选择性别',
            trigger: 'blur'
          }
        ],
        username: [
          {
            required: true,
            type: 'string',
            message: '用户不能为空',
            trigger: 'blur'
          },
          {
            min: 3,
            max: 30,
            message: '用户名长度在3-30位之间',
            trigger: 'blur'
          },
          {
            pattern: /^[0-9A-Za-z_]{3,30}$/,
            message: '用户名只能包含数字、字母、下划线',
            trigger: 'blur'
          },
          {
            validator: (rule, val, cb) => {
              let url = `teacher/repeat?username=${val}`
              if (this.editModal) url += `&id=${this.form.id}`
              this.$http.get(url).then(res => {
                if (res.code === 200) {
                  if (res.data.flag) {
                    return cb(new Error('用户名已存在！'))
                  }
                  cb()
                }
              })
            },
            trigger: 'blur'
          }
        ],
        password: [
          {
            required: false,
            type: 'string',
            trigger: 'blur'
          },
          {
            min: 6,
            max: 30,
            message: '密码长度在6-30位之间',
            trigger: 'blur'
          },
          {
            pattern: /^[a-zA-Z0-9-*/+.~!@#$%^&*()]{6,30}$/,
            message: '密码只能包含数字、字母、特殊字符',
            trigger: 'blur'
          }
        ],
        phone: [
          {
            required: true,
            type: 'string',
            message: '电话不能为空',
            trigger: 'blur'
          },
          {
            pattern: /^((13\d|14[57]|15[^4,\D]|17[678]|18\d)\d{8}|170[059]\d{7})$/,
            message: '电话号码格式不正确',
            trigger: 'blur'
          }
        ],
        email: [
          {
            required: true,
            type: 'string',
            message: '邮箱不能为空',
            trigger: 'blur'
          },
          {
            pattern: /^\w[-\w.+]*@([A-Za-z0-9][-A-Za-z0-9]*\.)+[A-Za-z]{2,14}$/,
            message: '电子邮箱格式不正确',
            trigger: 'blur'
          }
        ]
      },
      total: 0,
      current: 1,
      pageSize: 10,
      search: {},
      menuTreeData: [],
      menuTree: false,
      menuUserId: 0
    }
  },
  mounted () {
    this.getData()
  },
  computed: {
    modalShow: {
      get () {
        return this.addModal || this.editModal
      },
      set () {
        this.addModal = this.editModal = false
      }
    }
  },
  methods: {
    getData () {
      this.$http.post(`teacher/get?pageNo=${this.current}&pageSize=${this.pageSize}`, this.search).then(res => {
        this.current = res.data.page.current
        this.total = res.data.page.total
        this.data = res.data.page.records
      })
    },
    modalChange (v) {
      if (!v) {
        this.$refs.modalForm.resetFields()
        this.form = { status: true }
      }
    },
    userRoleClick () {
      this.$http.post('teacher/userRole', this.$qs.stringify({ userId: this.editRoleUserId, roles: this.userRoles }, { arrayFormat: 'repeat' })).then(res => {
        if (res.code === 200) {
          this.$Message.success(res.msg)
        }
        this.editRoleModal = false
      })
    },
    submit () {
      this.$refs.modalForm.validate((v) => {
        if (v) {
          if (this.addModal) {
            this.form.type = 2
            this.$http.post('teachers', this.form).then(res => {
              if (res.code === 200) {
                this.getData()
                this.$Message.success(res.msg)
                this.addModal = false
              }
            })
          }
          if (this.editModal) {
            this.form.updateTime = null
            this.$http.put('teachers', this.form).then(res => {
              if (res.code === 200) {
                this.getData()
                this.$Message.success(res.msg)
                this.editModal = false
              }
            })
          }
        }
      })
    },
    status (obj) {
      this.$http.post('teacher/status', this.form).then(res => {
        if (res.code === 200) {
          this.$Message.success(res.msg)
          obj.row.status = status
        }
      })
    },
    pageChange (index) {
      this.current = index
      this.getData()
    },
    pageSizeChange (size) {
      this.current = 1
      this.pageSize = size
      this.getData()
    },
    searchClick () {
      this.current = 1
      this.getData()
    },
    menuTreeOkClick () {
      this.$http.post('menu/userIdMenu', this.$qs.stringify({ userId: this.menuUserId, type: 2, menus: this.$refs.tree.getCheckedAndIndeterminateNodes().map(v => v.id) }, { arrayFormat: 'repeat' })).then(res => {
        if (res.code === 200) {
          this.$Message.success(res.msg)
          window.location.reload()
        }
        this.menuTree = false
      })
    }
  }
}
</script>

<style scoped lang="scss">
form {
  margin-top: 20px;
}
</style>
